package com.itcs.box.server.resolver;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.itcs.box.BoxConstants;
import com.itcs.box.domain.BoxResponse;
import com.itcs.box.server.server.NettyChannelMap;
import com.itcs.box.util.LogUtils;
import com.itcs.dubbo.service.DubboServiceAdapter;

/**
 * 发送车道交易完成结果
 * 
 * @author LiuPeng
 * @date 2017年12月12日
 * 
 */
@Component
public class Box2007Resolver implements DubboServiceAdapter {

	private Log logger = LogFactory.getLog(getClass());

	@Override
	public String getTrancode() {
		return "cbox_2007";
	}

	@Override
	public Map<String, Object> exchange(Map<String, Object> resMap) {
		LogUtils.LogInfo("Dubbo转发成功通知", getTrancode(), "", JSON.toJSONString(resMap), getClass());

		Object res = resMap.get(BoxConstants.BOX_REQ_KEY);
		if (res != null) {
			BoxResponse boxResponse = (BoxResponse) resMap.get(BoxConstants.BOX_REQ_KEY);
			String deviceId = boxResponse.getData().getDeviceId();

			// 向盒子推送消息
			Map<String, ChannelHandlerContext> map = NettyChannelMap.getMap();

			if (boxResponse == null || map.size() < 1 || map.get(deviceId) == null) {
				LogUtils.LogInfo("Dubbo转发成功通知-缺少返回数据或" + deviceId + "已离线", getTrancode(), "", JSON.toJSONString(resMap), getClass());
			}

			ChannelHandlerContext channel = map.get(deviceId);
			if (channel == null) {
				LogUtils.LogInfo("Dubbo转发APP,异常，找不到channel", getTrancode(), "", JSON.toJSONString(resMap), getClass());
				return null;
			}

			ByteBuf byteBuf = Unpooled.wrappedBuffer(JSON.toJSONString(boxResponse).getBytes(BoxConstants.CHARSET_UTF8));
			channel.writeAndFlush(byteBuf);

			LogUtils.LogInfo("成功通知", getTrancode(), boxResponse.getData().getTransacSeq(), JSON.toJSONString(boxResponse), getClass());
		} else {
			LogUtils.LogInfo("Dubbo转发成功通知-缺少返回数据", getTrancode(), "", JSON.toJSONString(resMap), getClass());
		}
		return null;
	}
}
